package com.maszy.pos;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.maszy.bean.CashRegister;
import com.maszy.bean.Log;
import com.maszy.commons.tools.Commons;
import com.maszy.commons.tools.SystemSet;
import com.maszy.db.ConfigurableConstants;
import com.maszy.service.CashRegisterService;
import com.maszy.service.PosService;

import cr5xdll.CR5XFrame;

public class PosFrame extends ConfigurableConstants {
	static {
		init("dir.properties");
	}
	CR5XFrame cf = new CR5XFrame();
	
	// 获取收银机列表
	public List<CashRegister> queryForAllCashRegister() {
		List<CashRegister> list = new ArrayList<CashRegister>();
		CashRegisterService crs = new CashRegisterService();
		list = crs.query();
		System.out.println("获取到收银机共" + list.size() + "台.");
		return list;
	}

	// 注册收银机并获取收银机日销售明细,返回上传的HEX文件列表
	public List TransUpTrRptAllRegister(List<CashRegister> list) {
		List hexList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			// 注册收银机
			long m = 10;
			boolean b = cf.regObj(list.get(i));

			if (b) {
				// 注册成功上传日销售明细
				String fileName = setFileName("TrRpt", list.get(i)
						.getCashRegister_NO(),"hex");
				int q = cf.TransUpTrRpt(
						Integer.parseInt(list.get(i).getCashRegister_NO()), fileName,
						posDir("log/TrRptLog")+"/TrRptLog_"+ list.get(i).getCashRegister_NO()+ "_"+ new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime())+".log");
									
				Log log=new Log();	
				labelA:
				while(!"OK".equals(Log.l)){
					if("Fail".equals(Log.l)){
						File file=new File(fileName);
						file.delete();
						break labelA;
					}
	
					try {
						Thread.sleep(6000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
				}
				if("OK".equals(Log.l)){
					hexList.add(fileName);	
				}					
				Log.l=null;				
			}		
		}
		System.out.println("获取销售明细HEX文件共" + hexList.size() + "个.");
		return hexList;
	}
	
	// 将已上传的销售明细HEX文件都转为TXT
	public boolean TrRptToTxt(String str) {	
	
		int i = 0;		
		boolean f = false;
		boolean b=false;
		labelB:
		f=Commons.fileIsIn(str);
		Thread t = new Thread();			
			if (f) {				
				String[] fileName = setTxtName(str);
				File file=new File(str);
				if(file.exists()){
					if(file.length()>0){
						b = cf.SaleDetailRptHexToTxt(str, fileName[0], fileName[1],
								fileName[2],posDir("err/TrRptErr")+"/TrRptErr_"+ new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime())+".err", false);
						System.out.println("已查询到HEX文件,正准备生成TXT");
					}else{
						f=file.delete();
						System.out.println(str+"文件长度为0,删除成功否："+f);
						if(!f){							
							file.delete();
						}
					}
				}			 			
				f=b;
			}else{
				System.out.println("未找到HEX文件!");
//				return f;
			}	
	
		return f;
	}
	// 将已上传的RFID会员卡HEX文件转为TXT
	public String RFIDToTxt(String str) {	
		
		int i = 0;		
		boolean f = false;
		boolean b=false;
		String fileName="";
			f=true;			
			if (f) {				
				fileName = txtName(str);
				File file=new File(str);
				if(file.exists()){
					if(file.length()>0){
						b = cf.RFIDHexToTxt(fileName,str, posDir("err/TrRptErr")+"/TrRptErr_"+ new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime())+".err", false);						
					}else{
						f=file.delete();
						System.out.println(str+"文件长度为0,删除成功否："+f);
						if(!f){							
							file.delete();
						}
					}
				}			 			
				f=b;
			}else{
				System.out.println("未找到HEX文件!");
//				return f;
			}	
		if(f){
			return fileName;
		}else{
			return null;
		}

	}
	// 将销售明细TXT文件录入数据库
	public void TrRptTxtToSQL(String str) {
		String[] fileName = setTxtName(str);
		for(int q=0;q<fileName.length;q++){
			System.out.println(fileName[q]);
		}
		int s = 0;
		Thread t = new Thread();
		boolean b = true;

		labelWhile: while (Commons.fileIsIn(fileName[0]) != true
				&& Commons.fileIsIn(fileName[1]) != true
				&& Commons.fileIsIn(fileName[2]) != true) {
			s++;
			
			try {
				if (s != 10) {
					b = true;
					t.sleep(5000);
					
				} else {
					b = false;
					t.join();
					break labelWhile;
				}

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
		// 解析total.TXT数据
		if (b) {
			File f = new File(fileName[0]);
			try {
				FileReader fileReader = new FileReader(f);
				BufferedReader bufferReader = null;
				try {
					InputStreamReader read = new InputStreamReader(
							new FileInputStream(f), "GBK");
					bufferReader = new BufferedReader(read);
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				String sss;
				try {
					sss = bufferReader.readLine();
					List list = new ArrayList();
					while ((sss = bufferReader.readLine()) != null) {

						String[] a = sss.split("\t");
						list.add(a);
					}
					for (int i = 0; i < list.size(); i++) {
						PosService ps = new PosService();
						ps.addTotal((String[]) list.get(i));
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 解析item.txt数据
			f = new File(fileName[1]);
			try {
				FileReader fileReader = new FileReader(f);
				BufferedReader bufferReader = null;
				try {
					InputStreamReader read = new InputStreamReader(
							new FileInputStream(f), "GBK");
					bufferReader = new BufferedReader(read);
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				String sss;
				try {
					sss = bufferReader.readLine();
					List list = new ArrayList();

					while ((sss = bufferReader.readLine()) != null) {
						String[] a = sss.split("\t");
						list.add(a);
					}
					for (int i = 0; i < list.size(); i++) {
						PosService ps = new PosService();
						ps.addItem((String[]) list.get(i));
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 解析pay.TXT数据
			f = new File(fileName[2]);
			try {
				FileReader fileReader = new FileReader(f);
				BufferedReader bufferReader = null;
				try {
					InputStreamReader read = new InputStreamReader(
							new FileInputStream(f), "GBK");
					bufferReader = new BufferedReader(read);
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				String sss;
				try {
					sss = bufferReader.readLine();
					List list = new ArrayList();
					while ((sss = bufferReader.readLine()) != null) {
						String[] a = sss.split("\t");
						list.add(a);
					}
					for (int i = 0; i < list.size(); i++) {
						PosService ps = new PosService();
						ps.addPay((String[]) list.get(i));
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("插入数据库成功");
		} else {
			System.out.println("未找到TXT文件,未插入数据库");
		}

	}

	// 设置文件上传目录
	public String posDir(String type) {
		// 创建上传目录
		String posDir = SystemSet.posDir;

		// String trRptDir = getProperty("Pos");

		boolean b = Commons.createFolder(posDir);
		if (b) {
			// 将收银目录说明文件复制到此文件夹根目录下

		}
		// 销售明细
		// trRptDir += getProperty(type);
		String trRptDir = posDir + type;
		Commons.createFolder(trRptDir);

		trRptDir = trRptDir
				+ "/"
				+ new SimpleDateFormat("yyyy-MM-dd").format(Calendar
						.getInstance().getTime());

		Commons.createFolder(trRptDir);
		System.out.println("文件上传至目录"+trRptDir);
		return trRptDir;
	}
	// 获取会员卡消费记录HEX文件,返回HEX文件列表。
	public List TransUpRfid(List<CashRegister> list) {
		List hexList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			// 注册收银机
			long m = 10;
			boolean b = cf.regObj(list.get(i));

			if (b) {
				// 注册成功上传会员卡消费明细及充值情况
				String fileName = setFileName("RFIDREC", list.get(i)
						.getCashRegister_NO(),"hex");
				int q = cf.TransUpRFID(
						Integer.parseInt(list.get(i).getCashRegister_NO()), fileName,
						posDir("log/RfidLog")+"/RfidLog_"+ new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime())+".log");	
				Log log=new Log();	
				labelA:
				while(!"OK".equals(Log.l)){
					if("Fail".equals(Log.l)){
						File file=new File(fileName);
						file.delete();
						break labelA;
					}
	
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
				}
				if("OK".equals(Log.l)){
					hexList.add(fileName);	
				}
					
				Log.l=null;				
			}			
		}
		return hexList;
	}
	//将RFID会员卡交易记录TXT文件录入数据库
	public void RFIDTxtToSQL(String str){
		File f = new File(str);
		System.out.println("RFID TXT文件名:"+str);
		try {
			FileReader fileReader = new FileReader(f);
			BufferedReader bufferReader = null;
			try {
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(f), "GBK");
				bufferReader = new BufferedReader(read);
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			String sss;
			try {
				sss = bufferReader.readLine();
				List list = new ArrayList();
				while ((sss = bufferReader.readLine()) != null) {
					String[] a = sss.split("\t");
					list.add(a);
				}
				for (int i = 0; i < list.size(); i++) {
					PosService ps = new PosService();
					ps.addRfid((String[]) list.get(i));
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 设置文件上传名称
	public String setFileName(String type, String CashRegister_Id,String fileType) {
		String fileName = type
				+ "_"
				+ CashRegister_Id
				+ "_"
				+ new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar
						.getInstance().getTime()) + "."+fileType;
		String dirName = posDir(type);
		return dirName + "/" + fileName;
	}

	// 设置销售明细TXT文件名称
	public String[] setTxtName(String hexName) {
		String[] a = hexName.split("[.]");
		a = a[0].split("_");
		String[] fileName = new String[3];
		String dirName = posDir("TrRptTxt");
		if (a.length == 3) {
			fileName[0] = dirName + "/" + a[1] + "_" + a[2] + "_total.txt";
			fileName[1] = dirName + "/" + a[1] + "_" + a[2] + "_item.txt";
			fileName[2] = dirName + "/" + a[1] + "_" + a[2] + "_pay.txt";
		}
		return fileName;
	}
	// 设置普通类型TXT文件名称
	public String txtName(String hexName) {
		String[] a = hexName.split("[.]");
		a = a[0].split("_");
		String fileName = new String();
		String dirName = posDir("RFIDTxt");
		if (a.length == 3) {
			fileName = dirName + "/" + a[1] + "_" + a[2] + ".txt";		
		}
		return fileName;
	}
	public static void main(String args[]){
		PosFrame pf=new PosFrame();
		String s=pf.posDir("log/TrRptLog")+"/TrRptLog_"+ "37001184"+ "_"+ new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime())+".log";
		System.out.println(s);
	}
}
